<template>
	<view class="gas-station-detail">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left">
				<uni-icons type="left" size="20" @click="goBack"></uni-icons>
			</view>
			<view class="navbar-title">加油站详情</view>
			<view class="navbar-right">
				<uni-icons type="more-filled" size="20" @click="showMoreOptions"></uni-icons>
			</view>
		</view>
		
		<!-- 加油站图片 -->
		<view class="station-image-container">
			<image :src="stationDetail.image" mode="aspectFill" class="station-image"></image>
		</view>
		
		<!-- 加油站基本信息 -->
		<view class="station-info">
			<view class="station-name">{{ stationDetail.name }}</view>
			<view class="station-hours">
				<text class="hours-label">营业时间:</text>
				<text class="hours-text">{{ stationDetail.openTime }}</text>
				<uni-icons type="phone" size="16" color="#007AFF" @click="callStation"></uni-icons>
			</view>
			<view class="station-address">
				<text class="address-text">{{ stationDetail.address }}</text>
				<uni-icons type="paperplane" size="16" color="#007AFF" @click="navigateToStation"></uni-icons>
			</view>
		</view>
		
		<!-- 油价详情 -->
		<view class="price-details">
			<view class="price-title">油价详情</view>
			<view class="price-list">
				<view class="price-item" v-for="(price, index) in fuelPrices" :key="index">
					<text class="fuel-type">{{ price.type }}</text>
					<text class="fuel-price">¥{{ price.price }}/L</text>
				</view>
			</view>
		</view>
		
		<!-- 服务项目 -->
		<view class="services-section" v-if="stationDetail.services && stationDetail.services.length > 0">
			<view class="services-title">服务项目</view>
			<view class="services-list">
				<view class="service-item" v-for="(service, index) in stationDetail.services" :key="index">
					<text class="service-text">{{ service }}</text>
				</view>
			</view>
		</view>
		
		<!-- 加油站描述 -->
		<view class="description-section" v-if="stationDetail.description">
			<view class="description-title">加油站介绍</view>
			<view class="description-content">{{ stationDetail.description }}</view>
		</view>
		
		<!-- 联系信息 -->
		<view class="contact-section" v-if="stationDetail.contact">
			<view class="contact-title">联系信息</view>
			<view class="contact-item">
				<text class="contact-label">联系电话:</text>
				<text class="contact-value">{{ stationDetail.contact }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';
	import { gasStationApi } from '@/api/index.js';
	
	export default {
		components: { 
			uniIcons
		},
		data() {
			return {
				stationId: null,
				stationDetail: {
					id: 1,
					name: '加载中...',
					price: '5.97',
					discount: '满200减20',
					address: '加载中...',
					distance: '0m',
					image: '/static/c1.png',
					latitude: 34.7478,
					longitude: 113.6254,
					rating: 4.5,
					openTime: '加载中...',
					services: ['加油', '洗车', '便利店'],
					description: '加载中...',
					contact: '加载中...',
					images: ['/static/c1.png'],
					fuelPrices: [] // 添加油价数组
				},
				fuelPrices: [
					{ type: '92#', price: '5.87' },
					{ type: '95#', price: '5.97' },
					{ type: '98#', price: '6.27' },
					{ type: '0#', price: '5.77' }
				]
			};
		},
		
		onShow() {
			console.log('页面显示');
			// 页面显示时不重新加载数据，保持当前状态
		},
		
		onLoad(options) {
			console.log('页面加载，参数:', options);
			
			// 获取传递的加油站ID
			if (options.id) {
				this.stationId = options.id;
				
				// 检查是否已经有缓存的数据
				const cachedData = uni.getStorageSync(`gasStation_${this.stationId}`);
				if (cachedData && Date.now() - cachedData.timestamp < 5 * 60 * 1000) { // 5分钟内的缓存有效
					console.log('使用缓存数据:', cachedData);
					this.stationDetail = cachedData.data;
					this.updateFuelPrices();
				} else {
					console.log('缓存数据不存在或已过期，重新加载');
					this.loadStationDetail();
				}
			} else {
				console.error('未传递加油站ID');
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				});
			}
		},
		methods: {
			// 加载加油站详情
			async loadStationDetail() {
				try {
					uni.showLoading({ title: '加载中...' });
					const result = await gasStationApi.getGasStationDetail(this.stationId);
					
					console.log('加油站详情API返回结果:', result);
					console.log('result.code:', result.code);
					console.log('result.data:', result.data);
					console.log('result.msg:', result.msg);
					
					// 根据你的request.js，API函数直接接收到{code, msg, data}格式
					if (result.code === 200) {
						// 转换后端数据为前端期望的格式
						this.stationDetail = this.convertBackendData(result.data);
						// 根据加油站信息更新油价
						this.updateFuelPrices();
						// 缓存数据
						uni.setStorageSync(`gasStation_${this.stationId}`, {
							data: this.stationDetail,
							timestamp: Date.now()
						});
					} else {
						uni.showToast({
							title: result.msg || '加载失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载加油站详情失败:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			
			// 转换后端数据为前端期望的格式
			convertBackendData(backendData) {
				console.log('开始转换后端数据，原始数据:', backendData);
				
				if (!backendData) {
					console.warn('后端数据为空');
					return this.stationDetail; // 返回默认数据
				}
				
				// 根据后端数据库字段进行转换
				const converted = {
					id: backendData.gasStationId || backendData.id,
					name: backendData.name || '未知加油站',
					address: backendData.address || '地址未知',
					image: backendData.img || '/static/gas-station-default.png',
					phone: backendData.phone || '暂无电话',
					week: backendData.week || '营业时间未知',
					message: backendData.message || '暂无优惠',
					longitude: backendData.longitude,
					latitude: backendData.latitude,
					// 前端期望的字段
					openTime: backendData.week || '营业时间未知',
					contact: backendData.phone || '暂无电话',
					description: backendData.message || '暂无描述',
					services: ['加油', '洗车', '便利店'], // 默认服务
					// 油价相关字段
					price: this.extractPriceFromMessage(backendData.message) || '价格未知',
					fuelPrices: this.generateFuelPrices(backendData.message)
				};
				
				console.log('转换后的数据:', converted);
				return converted;
			},
			
			// 从优惠信息中提取价格
			extractPriceFromMessage(message) {
				if (!message) return null;
				
				// 尝试从优惠信息中提取价格
				const priceMatch = message.match(/¥(\d+(?:\.\d+)?)/);
				if (priceMatch) {
					return priceMatch[1];
				}
				
				// 如果没有价格信息，返回默认值
				return '价格未知';
			},
			
			// 生成油价数据
			generateFuelPrices(message) {
				const basePrice = this.extractPriceFromMessage(message);
				if (basePrice && basePrice !== '价格未知') {
					const price = parseFloat(basePrice);
					return [
						{ type: '92#', price: (price - 0.1).toFixed(2) },
						{ type: '95#', price: price.toFixed(2) },
						{ type: '98#', price: (price + 0.3).toFixed(2) },
						{ type: '0#', price: (price - 0.2).toFixed(2) }
					];
				} else {
					// 使用默认价格
					return [
						{ type: '92#', price: '7.50' },
						{ type: '95#', price: '7.60' },
						{ type: '98#', price: '7.90' },
						{ type: '0#', price: '7.40' }
					];
				}
			},
			
			// 更新油价信息
			updateFuelPrices() {
				// 使用从API获取的真实油价数据
				if (this.stationDetail.fuelPrices && this.stationDetail.fuelPrices.length > 0) {
					this.fuelPrices = this.stationDetail.fuelPrices;
					console.log('使用API获取的真实油价:', this.fuelPrices);
				} else {
					// 如果没有获取到油价数据，使用默认价格
					const basePrice = parseFloat(this.stationDetail.price);
					if (!isNaN(basePrice)) {
						this.fuelPrices = [
							{ type: '92#', price: (basePrice - 0.1).toFixed(2) },
							{ type: '95#', price: basePrice.toFixed(2) },
							{ type: '98#', price: (basePrice + 0.3).toFixed(2) },
							{ type: '0#', price: (basePrice - 0.2).toFixed(2) }
						];
						console.log('使用默认计算的油价:', this.fuelPrices);
					} else {
						// 如果价格无效，使用默认价格
						this.fuelPrices = [
							{ type: '92#', price: '7.50' },
							{ type: '95#', price: '7.60' },
							{ type: '98#', price: '7.90' },
							{ type: '0#', price: '7.40' }
						];
						console.log('使用默认油价:', this.fuelPrices);
					}
				}
			},
			
			// 返回上一页
			goBack() {
				console.log('点击返回按钮');
				
				// 检查页面栈
				const pages = getCurrentPages();
				console.log('当前页面栈:', pages);
				
				if (pages.length > 1) {
					// 有上一页，直接返回
					console.log('返回上一页');
					uni.navigateBack({
						delta: 1,
						success: () => {
							console.log('返回成功');
						},
						fail: (err) => {
							console.error('返回失败:', err);
							// 如果返回失败，跳转到加油站列表页
							uni.navigateTo({
								url: '/pages/Fuel Nearby/Fuel Nearby'
							});
						}
					});
				} else {
					// 没有上一页，跳转到加油站列表页
					console.log('没有上一页，跳转到加油站列表页');
					uni.navigateTo({
						url: '/pages/Fuel Nearby/Fuel Nearby'
					});
				}
			},
			
			// 显示更多选项
			showMoreOptions() {
				uni.showActionSheet({
					itemList: ['分享', '收藏', '举报'],
					success: (res) => {
						if (res.tapIndex === 0) {
							this.shareStation();
						} else if (res.tapIndex === 1) {
							this.favoriteStation();
						} else if (res.tapIndex === 2) {
							this.reportStation();
						}
					}
				});
			},
			
			// 拨打电话
			callStation() {
				if (this.stationDetail.contact) {
					uni.makePhoneCall({
						phoneNumber: this.stationDetail.contact,
						success: () => {
							console.log('拨打电话成功');
						},
						fail: (err) => {
							console.error('拨打电话失败:', err);
							uni.showToast({
								title: '拨打电话失败',
								icon: 'none'
							});
						}
					});
				} else {
					uni.showToast({
						title: '暂无联系电话',
						icon: 'none'
					});
				}
			},
			
			// 导航到加油站
			navigateToStation() {
				console.log('导航到加油站:', this.stationDetail);
				
				// 检测当前运行环境
				// #ifdef H5
				// 在H5环境中，使用网页版地图
				this.openWebMap();
				// #endif
				
				// #ifdef APP-PLUS || MP
				// 在APP或小程序环境中，使用原生地图
				uni.openLocation({
					latitude: this.stationDetail.latitude,
					longitude: this.stationDetail.longitude,
					name: this.stationDetail.name,
					address: this.stationDetail.address,
					success: () => {
						console.log('导航成功');
					},
					fail: (err) => {
						console.error('导航失败:', err);
						uni.showToast({
							title: '导航失败',
							icon: 'none'
						});
					}
				});
				// #endif
			},
			
			// 在H5环境中打开网页版地图
			openWebMap() {
				// 构建Google Maps URL
				const googleMapUrl = `https://www.google.com/maps/search/?api=1&query=${this.stationDetail.latitude},${this.stationDetail.longitude}`;
				
				// 构建百度地图URL
				const baiduMapUrl = `https://api.map.baidu.com/marker?location=${this.stationDetail.latitude},${this.stationDetail.longitude}&title=${encodeURIComponent(this.stationDetail.name)}&content=${encodeURIComponent(this.stationDetail.address)}&output=html&src=webapp.baidu.openAPIdemo`;
				
				// 显示地图选择对话框
				uni.showActionSheet({
					itemList: ['Google地图', '百度地图'],
					success: (res) => {
						let mapUrl = '';
						switch (res.tapIndex) {
							case 0:
								mapUrl = googleMapUrl;
								break;
							case 1:
								mapUrl = baiduMapUrl;
								break;
						}
						
						if (mapUrl) {
							// 在新窗口中打开地图
							window.open(mapUrl, '_blank');
							
							uni.showToast({
								title: '已打开地图',
								icon: 'success'
							});
						}
					},
					fail: () => {
						// 用户取消选择，默认打开Google地图
						window.open(googleMapUrl, '_blank');
					}
				});
			},
			
			// 分享加油站
			shareStation() {
				uni.showToast({
					title: '分享功能开发中',
					icon: 'none'
				});
			},
			
			// 收藏加油站
			favoriteStation() {
				uni.showToast({
					title: '收藏成功',
					icon: 'success'
				});
			},
			
			// 举报加油站
			reportStation() {
				uni.showToast({
					title: '举报功能开发中',
					icon: 'none'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.gas-station-detail {
		min-height: 100vh;
		background-color: #f5f5f5;
		
		.custom-navbar {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 30rpx;
			background-color: #ffffff;
			border-bottom: 1px solid #f0f0f0;
			
			.navbar-left {
				width: 60rpx;
				display: flex;
				align-items: center;
			}
			
			.navbar-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333333;
			}
			
			.navbar-right {
				width: 60rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
			}
		}
		
		.station-image-container {
			width: 100%;
			height: 400rpx;
			overflow: hidden;
			
			.station-image {
				width: 100%;
				height: 100%;
			}
		}
		
		.station-info {
			background-color: #ffffff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			.station-name {
				font-size: 40rpx;
				font-weight: bold;
				color: #333333;
				margin-bottom: 20rpx;
			}
			
			.station-hours {
				display: flex;
				align-items: center;
				margin-bottom: 15rpx;
				
				.hours-label {
					font-size: 28rpx;
					color: #666666;
					margin-right: 10rpx;
				}
				
				.hours-text {
					flex: 1;
					font-size: 28rpx;
					color: #333333;
				}
			}
			
			.station-address {
				display: flex;
				align-items: center;
				
				.address-text {
					flex: 1;
					font-size: 28rpx;
					color: #666666;
				}
			}
		}
		
		.price-details {
			background-color: #ffffff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			.price-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
				margin-bottom: 20rpx;
			}
			
			.price-list {
				.price-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 15rpx 0;
					border-bottom: 1px solid #f0f0f0;
					
					&:last-child {
						border-bottom: none;
					}
					
					.fuel-type {
						font-size: 28rpx;
						color: #333333;
					}
					
					.fuel-price {
						font-size: 28rpx;
						color: #ff4757;
						font-weight: bold;
					}
				}
			}
		}
		
		.services-section {
			background-color: #ffffff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			.services-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
				margin-bottom: 20rpx;
			}
			
			.services-list {
				display: flex;
				flex-wrap: wrap;
				gap: 15rpx;
				
				.service-item {
					background-color: #f8f9fa;
					padding: 10rpx 20rpx;
					border-radius: 20rpx;
					
					.service-text {
						font-size: 24rpx;
						color: #666666;
					}
				}
			}
		}
		
		.description-section {
			background-color: #ffffff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			.description-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
				margin-bottom: 20rpx;
			}
			
			.description-content {
				font-size: 28rpx;
				color: #666666;
				line-height: 1.6;
			}
		}
		
		.contact-section {
			background-color: #ffffff;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			.contact-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333333;
				margin-bottom: 20rpx;
			}
			
			.contact-item {
				display: flex;
				align-items: center;
				
				.contact-label {
					font-size: 28rpx;
					color: #666666;
					margin-right: 10rpx;
				}
				
				.contact-value {
					font-size: 28rpx;
					color: #333333;
				}
			}
		}
	}
</style> 